package cc.rengu.igas.cops.core.service.trans.unionpay;

import cc.rengu.igas.channel.upqc.facade.request.B2COrderPayQueryRequest;
import cc.rengu.igas.channel.upqc.facade.response.B2COrderPayQueryResponse;
import cc.rengu.igas.channel.upqc.facade.result.Result;
import cc.rengu.igas.cops.common.enums.RespCodeEnum;
import cc.rengu.igas.cops.facade.bean.CouponInfo;
import cc.rengu.igas.cops.facade.request.BankB2cOrderPayQueryRequest;
import cc.rengu.igas.cops.facade.response.BankB2cOrderPayQueryResponse;
import cc.rengu.oltp.service.base.BizBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.RiskMonitorInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.OrderService;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.TransCustomImpl;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.service.realize.impl.OrderServiceImpl;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.BeanUtil;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;

/**
 * 主扫---付款查询
 * 手机【ESB】—>支付—>通道—>银联（同步接口，银联扣款后返回结果）
 * <p>
 * 订单表字段：
 * remark2：二维码类型
 * remark3：优惠信息json list
 * front_seq_num前端流水号：付款凭证号
 *
 * @author panky
 * @version 1.0.0 创建时间：2020.06.23
 */
public class BankB2cOrderPayQueryService extends BizBaseService implements TransCustomImpl {

    @Override
    protected Object beforeBizProcess() throws Exception {
        BankB2cOrderPayQueryRequest bankB2cOrderPayQueryRequest = new BankB2cOrderPayQueryRequest();
        ConvertUtil.convertOutput(bankB2cOrderPayQueryRequest);
        return bankB2cOrderPayQueryRequest;
    }

    @Override
    protected BizResponse callBizService(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        // 录入参数
        BankB2cOrderPayQueryRequest bankB2cOrderPayQueryRequest = (BankB2cOrderPayQueryRequest) request;
        // 行号
        String instId = bankB2cOrderPayQueryRequest.getHeader().getInstId();

        // 获取用户订单信息表
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();

        UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByPrimaryKey(instId, bankB2cOrderPayQueryRequest.getTxnNo());
        if (null == userOrderInfo) {
            rglog.debug("查询用户订单表异常");
            throw new BizException(OltpRpcdEnum.RECOND_EMPTY_OR_NOT_FOUND.getRespCode(), OltpRpcdEnum.RECOND_EMPTY_OR_NOT_FOUND.getRespDesc());
        }

        // 订单初始状态去查询
        if (BizStatusEnum.INIT.getStatus().equals(userOrderInfo.getBizStatus())
                || BizStatusEnum.PROCESSING.getStatus().equals(userOrderInfo.getBizStatus())) {
            queryStt(userOrderInfo, bankB2cOrderPayQueryRequest);
        }

        BankB2cOrderPayQueryResponse bankB2cOrderPayQueryResponse = new BankB2cOrderPayQueryResponse();
        bankB2cOrderPayQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bankB2cOrderPayQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        // 交易状态
        bankB2cOrderPayQueryResponse.setTransStt(userOrderInfo.getTransStatus());
        bankB2cOrderPayQueryResponse.setVoucherNum(userOrderInfo.getFrontSeqNum());
        // 订单编号
        bankB2cOrderPayQueryResponse.setOrderNo(userOrderInfo.getMchntOrderId());
        // 订单真实金额
        bankB2cOrderPayQueryResponse.setOrderAmt(userOrderInfo.getRealPayAmt());
        // 实际优惠金额
        bankB2cOrderPayQueryResponse.setDiscountAmt(userOrderInfo.getRealDiscountAmt());
        // 商户名
        bankB2cOrderPayQueryResponse.setMchntName(userOrderInfo.getGroupMchntName());
        if (!StringUtil.isEmptyOrNull(userOrderInfo.getDiscountInfo())) {
            List<CouponInfo> couponInfoBeanList = JSON.parseArray(userOrderInfo.getDiscountInfo(), CouponInfo.class);
            // 存在优惠
            if (couponInfoBeanList != null && couponInfoBeanList.size() != 0) {
                bankB2cOrderPayQueryResponse.setCouponInfo(couponInfoBeanList.get(0));
            }
        }

        BizResponse bizResponse = new BizResponse();
        // 返回
        bizResponse.setResult(bankB2cOrderPayQueryResponse);// 返回结果
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    private B2COrderPayQueryResponse queryStt(UserOrderInfo userOrderInfo,
                                              BankB2cOrderPayQueryRequest bankB2cOrderPayQueryRequest) throws Exception {

        SysParamService sysParamService = new SysParamServiceImpl();
        /* 银联码，获取法人行在银联的机构号 */
        SysParam unionPayCode = sysParamService.getSysParamInfo(bankB2cOrderPayQueryRequest.getHeader().getInstId(),
                "OPMS_SYS_PARAM",
                "unionPayerOrgCode" + "_" + bankB2cOrderPayQueryRequest.getQddm());
        if (null == unionPayCode) {
            rglog.error("获取二维码服务失败！获取法人行在银联的机构号失败！instId:{}", bankB2cOrderPayQueryRequest.getHeader().getInstId());
            throw new BizException(RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespCode(), RespCodeEnum.MCHNT_INFO_NOT_FOUND.getRespDesc());
        }
        // 银联机构号
        String strUnonPayCode = unionPayCode.getParamValue();

        B2COrderPayQueryRequest b2COrderPayQueryRequest = new B2COrderPayQueryRequest();
        // 银联机构号
        b2COrderPayQueryRequest.setIssInsCode(strUnonPayCode);
        //交易顺序号	txnNo
        b2COrderPayQueryRequest.setTxnNo(userOrderInfo.getSysSeqNum());

        cc.rengu.igas.channel.upqc.facade.base.Header upHeader = new cc.rengu.igas.channel.upqc.facade.base.Header();
        BeanUtil.beanCopy(bankB2cOrderPayQueryRequest.getHeader(), upHeader);
        upHeader.setTxnNum("0140000903");// 查询营销
        upHeader.setSrcSysId("OPMS");
        b2COrderPayQueryRequest.setHeader(upHeader);

        // 去银联查询状态
        DubboService dubboService = new DubboServiceImpl();
        Result<B2COrderPayQueryResponse> responseResult = (Result<B2COrderPayQueryResponse>) dubboService.callDubboService("upqcPayerService", "b2cOrderPayQuery", b2COrderPayQueryRequest);
        if (null == responseResult || !responseResult.isSuccess() || !"00000000".equals(responseResult.getResult().getRespCode())) {
            rglog.error("调用银联主扫二维码付款，订单号<{}>信息失败,iReturnCode:<{}>",
                    bankB2cOrderPayQueryRequest.getTxnNo(),
                    responseResult.getResult().getRespCode(),
                    responseResult.getResult().getRespDesc());
        }
        rglog.info("调用银联主扫二维码付款，订单号<{}>,iReturnCode:<{}>",
                bankB2cOrderPayQueryRequest.getTxnNo(),
                responseResult.getResult().getRespCode(),
                responseResult.getResult().getRespDesc());

        B2COrderPayQueryResponse b2COrderPayQueryResponse = responseResult.getResult();

        // 业务状态
        // 非正常状态更新失败
        if ("00000000".equals(b2COrderPayQueryResponse.getRespCode())) {
            // 更新为失败
            userOrderInfo.setTransStatus(TransStatusEnum.TRANS_SUCC.getStatus());
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
        }
        // 01 :交易失败
        // 20：二维码已失效
        else if ("01".equals(b2COrderPayQueryResponse.getRespCode())) {
            // 更新为失败
            userOrderInfo.setTransStatus(TransStatusEnum.SYSTEM_REJECT.getStatus());
            userOrderInfo.setOrderStatus(OrderStatusEnum.FINISH.getStatus());
            userOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
        }

        if (!StringUtil.isEmptyOrNull(b2COrderPayQueryResponse.getVoucherNum())) {
            // 付款信息凭证号
            userOrderInfo.setFrontSeqNum(b2COrderPayQueryResponse.getVoucherNum());
        }

        OrderService orderService = new OrderServiceImpl();
        // 更新状态
        boolean isOrderCode = orderService.updateOrderInfo(userOrderInfo, null, null);
        if (!isOrderCode) {
            rglog.error("更新用户订单表失败!");
            throw new BizException(RespCodeEnum.UPDATE_ORDER_ERROR.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
        }

        return b2COrderPayQueryResponse;
    }

    @Override
    protected void afterBizProcess(BizResponse response) throws Exception {
        BankB2cOrderPayQueryResponse retResponse = (BankB2cOrderPayQueryResponse) response.getResult();
        ConvertUtil.convertInput(retResponse);
    }

    @Override
    protected RiskMonitorInfo getRiskMonitorInfo() {
        return null;
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        return null;
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        return null;
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        return null;
    }
}
